package com.netty.cn.model.websocket;

import java.util.concurrent.TimeUnit;

import com.netty.cn.model.websocket.handler.WebSocketHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;

/**
 * 
 * @author wangzonghui
 * @date 2021-08-06 11:09:48
 * @Description websocket 服务启动成功
 */
public class WebSocketServer {
	
	@SuppressWarnings("rawtypes")
	public static void main(String[] args) {
		
		int port=8888;
		
        EventLoopGroup masterEventLoopGroup = new NioEventLoopGroup();
        EventLoopGroup slaveEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        ChannelFuture channelFuture = bootstrap.group(masterEventLoopGroup, slaveEventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
 
                        pipeline.addLast(new WebSocketServerProtocolHandler("/"));
 
                        // 在10秒之内收不到消息自动断开
                        pipeline.addLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS));
                        pipeline.addLast(new WebSocketHandler());
                    }
                })
                .bind(port);
        try {
            channelFuture.sync();
            System.out.println("webSocket 服务启动成功，连接地址：ws://127.0.0.1:8888 ，浏览器测试地址：http://127.0.0.1:8888/");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
    }

}
